import random

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from luffyapi.settings import constants
from .models import User
from .serializers import UserModelSerializer
from .utils import get_user_by_account
import logging

log = logging.getLogger("django")


class UserAPIView(CreateAPIView):
    """用户信息视图"""
    queryset = User.objects.all()
    serializer_class = UserModelSerializer


class SMSAPIView(APIView):
    def get(self, request):
        """短信发送"""

        # 1. 判断手机号码是否在60秒内曾经发送过短信
        mobile = self.request.query_params.get('mobile')
        redis_conn = get_redis_connection("sms_code")
        ret = redis_conn.get("mobile_%s" % mobile)
        if ret is not None:
            return Response({"message": "对不起，60秒内已经发送过短信，请耐心等待"}, status=status.HTTP_400_BAD_REQUEST)

        # 2. 生成短信验证码
        sms_code = "%06d" % random.randint(1, 999999)

        # 3. 保存短信验证码到redis[使用事务把多条命令集中发送给redis]
        # 创建管道对象
        pipe = redis_conn.pipeline()
        # 开启事务【无法管理数据库的读取数据操作】
        pipe.multi()
        # 把事务中要完成的所有操作，写入到管道中
        pipe.setex("sms_%s" % mobile, constants.SMS_EXPIRE_TIME, sms_code)
        pipe.setex("mobile_%s" % mobile, constants.SMS_INTERVAL_TIME, "_")
        # 执行事务
        pipe.execute()

        # 5. 响应发送短信的结果
        return Response({"message": "发送短信成功！", "sms_code": sms_code})
